package com.mxx.common.payment;


import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Map;

/**
 * @Author itzgyw
 * @Date 2020-03-07
 * @Time 11:57
 * @Description:
 */
@Data
@Accessors(chain = true)
public class PayResponse {
    /**
     * 支付方订单id
     */
    private String transactionId;
    /**
     * 我方订单id
     */
    private String outTradeNo;
    /**
     * 我传输信道标识
     */
    private String attach;
    /**
     * 返回代码
     */
    private String resultCode;
    /**
     * 错误代码
     */
    private String failCode;
    /**
     * 错误信息
     */
    private String failMsg;
    /**
     * 用户打开微信id
     */
    private String userOpenId;
    /**
     * 订单状态
     */
    private String tradeState;
    /**
     * 订单状态描述
     */
    private String tradeStateDesc;

    /**
     * 退款状态
     * WeChat：
     * SUCCESS—退款成功
     * REFUNDCLOSE—退款关闭
     * PROCESSING—退款处理中
     * CHANGE—退款异常
     * Alipay
     * SUCCESS
     * Apple
     * SUCCESS
     */
    private String refundStatus;

    /**
     * 子订单ID
     */
    private String outRequestNo;

    /**
     * 微信支付回调解析
     */
    public static PayResponse createWeChatQueryAndNotifyResponse(Map<String, String> resultModel) {
        PayResponse response = new PayResponse();
        response.transactionId = resultModel.get("transaction_id");
        response.outTradeNo = resultModel.get("out_trade_no");
        response.attach = resultModel.get("attach");
        response.resultCode = resultModel.get("result_code");
        response.failCode = resultModel.get("err_code");
        response.failMsg = resultModel.get("err_code_des");
        response.userOpenId = resultModel.get("openid");
        response.tradeState = resultModel.get("trade_state");
        response.tradeStateDesc = resultModel.get("trade_state_desc");
        return response;
    }

    /**
     * 微信退款回调
     */
    public static PayResponse createWeChatRefundQueryAndNotifyResponse(Map<String, String> resultModel) {
        PayResponse response = new PayResponse();
        response.transactionId = resultModel.get("transaction_id");
        response.outTradeNo = resultModel.get("out_trade_no");
        response.outRequestNo = resultModel.get("out_refund_no");
        response.refundStatus = resultModel.get("refund_status");
        return response;
    }

    public static PayResponse createWeChatCloseResponse(Map<String, String> resultModel) {
        PayResponse response = new PayResponse();
        response.resultCode = resultModel.get("result_code");
        response.failCode = resultModel.get("err_code");
        response.failMsg = resultModel.get("err_code_des");
        return response;
    }

    /**
     * 微信退款执行返回
     */
    public static PayResponse createWeChatRefundResponse(Map<String, String> resultModel) {
        PayResponse response = new PayResponse();
        response.refundStatus = resultModel.get("result_code");
        response.failCode = resultModel.get("err_code");
        response.failMsg = resultModel.get("err_code_des");
        return response;
    }

    /**
     * 支付宝订单查询
     */
    public static PayResponse createAliQueryResponse(AlipayTradeQueryResponse queryResponse) {
        PayResponse response = new PayResponse();
        response.outTradeNo = queryResponse.getOutTradeNo();
        response.transactionId = queryResponse.getTradeNo();
        response.resultCode = queryResponse.getCode();
        if (!queryResponse.isSuccess()) {
            response.failCode = queryResponse.getSubCode();
            response.failMsg = queryResponse.getSubMsg();
        }
        response.userOpenId = queryResponse.getOpenId();
        response.tradeState = queryResponse.getTradeStatus();
        response.tradeStateDesc = queryResponse.getAuthTradePayMode();
        return response;
    }

    /**
     * 支付宝退款查询
     */
    public static PayResponse createAliRefundQueryResponse(AlipayTradeFastpayRefundQueryResponse queryResponse) {
        PayResponse response = new PayResponse();
        response.outTradeNo = queryResponse.getOutTradeNo();
        response.transactionId = queryResponse.getTradeNo();
        response.resultCode = queryResponse.getCode();
        response.outRequestNo = queryResponse.getOutRequestNo();
        if (!queryResponse.isSuccess()) {
            response.failCode = queryResponse.getSubCode();
            response.failMsg = queryResponse.getSubMsg();
        }

        // code=10000, refund_status为空或为REFUND_SUCCESS，代表退款成功
        if ("10000".equals(queryResponse.getCode())) {
            String refundStatus = queryResponse.getRefundStatus();
            if (refundStatus == null || "REFUND_SUCCESS".equals(refundStatus)) {
                response.refundStatus = "SUCCESS";
            }
        }
        return response;
    }

    public static PayResponse createAliPayNotifyFailResponse() {
        PayResponse payResponse = new PayResponse();
        payResponse.setFailCode("FAIL");
        payResponse.setFailMsg("支付宝支付:异步回掉验签错误");
        payResponse.setResultCode("FAIL");
        return payResponse;
    }

    /**
     * 支付宝下单回调以及退款回调
     *
     * @param entity entity
     */
    public static PayResponse createAliPayNotifyOkResponse(Map<String, String> entity) {
        PayResponse payResponse = new PayResponse();
        payResponse.setOutTradeNo(entity.get("out_trade_no"));
        payResponse.setTransactionId(entity.get("trade_no"));
        payResponse.setAttach(entity.get("passback_params"));
        payResponse.setTradeState(entity.get("trade_status"));

        // 退款通知必填参数：out_biz_no（商户订单号）、refund_fee（本次退款金额）、gmt_refund（退款时间）
        payResponse.setOutRequestNo(entity.get("out_biz_no"));
        if (payResponse.getOutRequestNo() != null) {
            if (entity.get("gmt_refund") != null) {
                payResponse.setRefundStatus("SUCCESS");
            }
        }
        return payResponse;
    }

    public static PayResponse createAliCloseResponse(AlipayTradeCloseResponse queryResponse) {
        PayResponse response = new PayResponse();
        response.outTradeNo = queryResponse.getOutTradeNo();
        response.transactionId = queryResponse.getTradeNo();
        response.attach = queryResponse.getTradeNo();

        response.resultCode = queryResponse.getCode();
        if (!queryResponse.isSuccess()) {
            response.failCode = queryResponse.getSubCode();
            response.failMsg = queryResponse.getSubMsg();
        }
        return response;
    }

    public static PayResponse createAliRefundResponse(AlipayTradeRefundResponse refundResponse) {
        PayResponse response = new PayResponse();
        response.outTradeNo = refundResponse.getOutTradeNo();
        response.transactionId = refundResponse.getTradeNo();

        // 支付宝全额退款没有回调
        if ("10000".equals(refundResponse.getCode()) && "Y".equals(refundResponse.getFundChange())) {
            response.refundStatus = "SUCCESS";
        } else if ("10000".equals(refundResponse.getCode()) && "N".equals(refundResponse.getFundChange())) {
            response.refundStatus = "REFUNDED";
        }
        response.resultCode = refundResponse.getCode();
        if (!refundResponse.isSuccess()) {
            response.failCode = refundResponse.getSubCode();
            response.failMsg = refundResponse.getSubMsg();
        }
        return response;
    }
}
